package com.qf.reliable;

import com.qf.util.ConnectionUtil;
import com.rabbitmq.client.*;
import org.junit.Test;

import java.io.IOException;

/**
 * 保证消息一定能送达到exchange  And  Queue   And Queue 持久化 message
 * @author zjw
 */
public class Publisher {

    @Test
    public void publish() throws Exception {
        //1. 构建connection
        Connection connection = ConnectionUtil.getConnection();

        //2. 构建channel
        Channel channel = connection.openChannel().get();

        channel.confirmSelect();
        channel.addConfirmListener(new ConfirmListener() {
            @Override
            public void handleAck(long deliveryTag, boolean multiple) throws IOException {
                System.out.println("消息成功的送达到交换机！！");
            }

            @Override
            public void handleNack(long deliveryTag, boolean multiple) throws IOException {
                System.out.println("消息没有送达到交换机！！");
            }
        });
        channel.addReturnListener(new ReturnListener() {
            @Override
            public void handleReturn(int replyCode, String replyText, String exchange, String routingKey, AMQP.BasicProperties properties, byte[] body) throws IOException {
                System.out.println("return方法执行了，消息没有路由到Queue，消息为：" + new String(body));
            }
        });
        //3. 发送消息
        AMQP.BasicProperties props = new AMQP.BasicProperties.Builder().deliveryMode(2).build();
        channel.basicPublish("","hello_queue",true,props,"可靠性".getBytes());


        System.in.read();

        //4. 释放资源
        channel.close();
        connection.close();
    }



}
